package com.huaxin.hxmodulemqtt.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class MqttMessageService implements MessageHandler {

    private final DataParsingServiceImpl dataParsingService;
    private static final Logger log = LoggerFactory.getLogger(MqttMessageService.class);

    // ✅ 添加 @ServiceActivator，绑定到 mqttInputChannel
    @ServiceActivator(inputChannel = "mqttInputChannel")
    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
        String topic = (String) message.getHeaders().get("mqtt_receivedTopic");
        Integer qos = (Integer) message.getHeaders().get("mqtt_qos");
        Boolean isRetained = Boolean.TRUE.equals(message.getHeaders().get("mqtt_retained"));

        Object payload = message.getPayload();
        String payloadStr = (payload instanceof byte[])
                ? new String((byte[]) payload)
                : payload.toString();

//        log.info("✅ MQTT 消息接收 | 主题: {} | QoS: {} | 保留: {} | 数据: {}",
//                topic, qos, isRetained, payloadStr);
        try {
            dataParsingService.parseData(topic, payloadStr);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}